package com.store.app.imlife.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.livecloud.live.AlivcMediaFormat;
import com.alibaba.livecloud.live.AlivcMediaRecorder;
import com.alibaba.livecloud.live.AlivcMediaRecorderFactory;
import com.alibaba.livecloud.live.AlivcStatusCode;
import com.alibaba.livecloud.live.OnLiveRecordErrorListener;
import com.alibaba.livecloud.live.OnNetworkStatusListener;
import com.alibaba.livecloud.live.OnRecordStatusListener;
import com.duanqu.qupai.jni.ApplicationGlue;
import com.duanqu.qupai.logger.DataStatistics;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.HyUserDao;
import com.hyphenate.easeui.model.recordBean_hy;
import com.hyphenate.easeui.ui.EaseBaseActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.bean.LiveBean;
import com.store.app.http.Stores;
import com.store.app.hyphenate.EaseChatFragment_Live;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

//import com.duanqu.qupai.logger.RecordLoggerManager;

/**
 * author:杭州短趣网络传媒技术有限公司
 * date:2016/6/27
 * description:LiveCameraActivity
 */
public class LiveCameraActivity extends EaseBaseActivity implements View.OnClickListener, IOnHttpListener {
    private static final String TAG = "DQLiveLiveDemo";
    //推流地址
    private String pushUrl = "";
    private  String posturl_1="rtmp://video-center.alivecdn.com/diandong/android"+ MainActivity.member_id+"?vhost=stream.meitianhui.com";

    //播放地址 用于给本地生活播放
    private String playUrl="";
    private static final int PERMISSION_REQUEST_CODE = 1;
    private static final String[] permissionManifest = {
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
    };

    private SurfaceView _CameraSurface;
    private AlivcMediaRecorder mMediaRecorder;

    private Surface mPreviewSurface;
    private Map<String, Object> mConfigure = new HashMap<>();
    private boolean isRecording = false;
    private int mPreviewWidth = 0;
    private int mPreviewHeight = 0;
    private DataStatistics mDataStatistics = new DataStatistics(1000);

    private final int PERMISSION_DELAY = 100;
    private boolean mHasPermission = false;
    private NetRequest netRequest;

    private ProgressDialog mProgressDialog;
    private String room_id;//聊天室id
    private EaseChatFragment_Live chatFragment;

    //判断直播是不有崩溃没解散聊天室的情况
    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    private TextView tv_camera;//切换摄像头
    private TextView tv_beauty;//美颜
    private TextView tvReturn;//返回
    private ImageView img_head;//头像
    private boolean ifOpenBeauty = false;//是否打开美颜
    //数据库存储
    private DBHelper_hy db=null;
    private recordBean_hy rb=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        RecordLoggerManager.createLoggerFile();
        System.loadLibrary("gnustl_shared");
        System.loadLibrary("qupai-media-thirdparty");
        System.loadLibrary("qupai-media-jni");
        ApplicationGlue.initialize(this);
        netRequest = new NetRequest(this);
        setContentView(R.layout.activity_live_camera);
        if (Build.VERSION.SDK_INT >= 23) {
            permissionCheck();
        }else {
            mHasPermission = true;
        }

        if(db==null){
            db=new DBHelper_hy(this);
            rb=new recordBean_hy();
        }


        //配置推流url
        long millis=  System.currentTimeMillis()/1000+3600;
        pushUrl="/diandong/android"+ MainActivity.member_id+"-"+millis+"-0-0-abc123";
        String s_md5 =MD5(pushUrl);
        pushUrl=posturl_1+"&auth_key="+millis+"-0-0-"+s_md5;


        //配置播放url
        millis=  System.currentTimeMillis()/1000+3600;
        s_md5 =MD5("/diandong/android"+ MainActivity.member_id+".flv-"+millis+"-0-0-abc123");
        playUrl="http://stream.meitianhui.com/diandong/android"+ MainActivity.member_id+".flv?auth_key="+millis+"-0-0-"+s_md5;
        Log.i("mylogplay",playUrl);
      //  http://stream.meitianhui.com/diandong/android3295a61d-dece-11e5-8f52-00163e0009c6.flv?auth_key=1494314946-0-0-73b40a5cd0f3bbe61e3f034442178a4f
        initView();


        //采集
        _CameraSurface = (SurfaceView) findViewById(R.id.camera_surface);
        _CameraSurface.getHolder().addCallback(_CameraSurfaceCallback);
        _CameraSurface.setOnTouchListener(mOnTouchListener);

        //对焦，缩放
        mDetector = new GestureDetector(_CameraSurface.getContext(), mGestureDetector);
        mScaleDetector = new ScaleGestureDetector(_CameraSurface.getContext(), mScaleGestureListener);

        mMediaRecorder = AlivcMediaRecorderFactory.createMediaRecorder();
        mMediaRecorder.init(this);

        mDataStatistics.start();
        mMediaRecorder.setOnRecordStatusListener(mRecordStatusListener);
        mMediaRecorder.setOnNetworkStatusListener(mOnNetworkStatusListener);
        mMediaRecorder.setOnRecordErrorListener(mOnErrorListener);

        mConfigure.put(AlivcMediaFormat.KEY_CAMERA_FACING, AlivcMediaFormat.CAMERA_FACING_FRONT);
        mConfigure.put(AlivcMediaFormat.KEY_MAX_ZOOM_LEVEL, 3);
        mConfigure.put(AlivcMediaFormat.KEY_OUTPUT_RESOLUTION, AlivcMediaFormat.OUTPUT_RESOLUTION_480P);
        mConfigure.put(AlivcMediaFormat.KEY_MAX_VIDEO_BITRATE, 800000);
        mConfigure.put(AlivcMediaFormat.KEY_DISPLAY_ROTATION, true ? AlivcMediaFormat.DISPLAY_ROTATION_90 : AlivcMediaFormat.DISPLAY_ROTATION_0);
        mConfigure.put(AlivcMediaFormat.KEY_EXPOSURE_COMPENSATION, -1);//曝光度-1为自动曝光
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
//        pushUrl = FileUtil.getSDCardPath()+ File.separator+sdf.format(new Date(System.currentTimeMillis()))+".flv";
        EventBus.getDefault().register(this);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = preferences.edit();



    }




    private void permissionCheck() {
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        for (String permission : permissionManifest) {
            if (PermissionChecker.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionCheck = PackageManager.PERMISSION_DENIED;
            }
        }
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, permissionManifest, PERMISSION_REQUEST_CODE);
        }else {
            mHasPermission = true;
        }
    }

    private void initView() {
        tv_camera = (TextView) findViewById(R.id.tv_camera);
        tv_camera.setOnClickListener(this);
        tv_beauty = (TextView) findViewById(R.id.tv_beauty);
        tv_beauty.setOnClickListener(this);
        tvReturn = (TextView) findViewById(R.id.tv_return);
        tvReturn.setOnClickListener(this);
        img_head=(ImageView) findViewById(R.id.iv_userhead);
        HyUserDao hyUserDao=rb.findMember_other(db,EMClient.getInstance().getCurrentUser());
        String url="";
        if(hyUserDao!=null){
            url=hyUserDao.getFaceimg();
        }
        if(TextUtils.isEmpty(url)){
            url="null";
        }
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .showImageOnLoading(R.drawable.ease_default_avatar)
                .showImageOnFail(R.drawable.ease_default_avatar)
                .showStubImage(R.drawable.ease_default_avatar)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(url, img_head,options);

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        if (mPreviewSurface != null) {
            mMediaRecorder.prepare(mConfigure, mPreviewSurface);
        }
           }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        if (isRecording) {
            mMediaRecorder.stopRecord();
        }
        /**
         * 如果要调用stopRecord和reset()方法，则stopRecord（）必须在reset之前调用，否则将会抛出IllegalStateException
         */
        mMediaRecorder.reset();
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("mylog", "onDestroy");
//        RecordLoggerManager.closeLoggerFile();
        EventBus.getDefault().unregister(this);
        mDataStatistics.stop();
        mMediaRecorder.release();
        if (editor != null) {
            editor.putString("live_room_id", "").apply();
        }
    }




    private GestureDetector mDetector;
    private ScaleGestureDetector mScaleDetector;
    private GestureDetector.OnGestureListener mGestureDetector = new GestureDetector.OnGestureListener() {
        @Override
        public boolean onDown(MotionEvent motionEvent) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent motionEvent) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent motionEvent) {
            if (mPreviewWidth > 0 && mPreviewHeight > 0) {
                float x = motionEvent.getX() / mPreviewWidth;
                float y = motionEvent.getY() / mPreviewHeight;
                mMediaRecorder.focusing(x, y);

            }
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent motionEvent) {

        }

        @Override
        public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
            return false;
        }
    };

    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mDetector.onTouchEvent(motionEvent);
            mScaleDetector.onTouchEvent(motionEvent);
            return true;
        }
    };

    private ScaleGestureDetector.OnScaleGestureListener mScaleGestureListener = new ScaleGestureDetector.OnScaleGestureListener() {
        @Override
        public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
            Log.d(TAG, "scale" + scaleGestureDetector.getScaleFactor());
            mMediaRecorder.setZoom(scaleGestureDetector.getScaleFactor());
            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {
        }
    };

    private final SurfaceHolder.Callback _CameraSurfaceCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            holder.setKeepScreenOn(true);
            mPreviewSurface = holder.getSurface();
            startPreview(holder);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            try {
                mMediaRecorder.setPreviewSize(width, height);
                mPreviewWidth = width;
                mPreviewHeight = height;
            }catch (NullPointerException e){

            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            mPreviewSurface = null;
            mMediaRecorder.stopRecord();
            mMediaRecorder.reset();
        }
    };


    private void startPreview(final SurfaceHolder holder) {
        if(!mHasPermission) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startPreview(holder);
                }
            }, PERMISSION_DELAY);
            return;
        }
        mMediaRecorder.prepare(mConfigure, mPreviewSurface);
        mMediaRecorder.setPreviewSize(_CameraSurface.getMeasuredWidth(), _CameraSurface.getMeasuredHeight());
        if ((int) mConfigure.get(AlivcMediaFormat.KEY_CAMERA_FACING) == AlivcMediaFormat.CAMERA_FACING_FRONT) {
            mMediaRecorder.addFlag(AlivcMediaFormat.FLAG_BEAUTY_ON);
        }
    }
    private boolean isSessionAttach=false;
    private OnRecordStatusListener mRecordStatusListener = new OnRecordStatusListener() {
        @Override
        public void onDeviceAttach() {
            mMediaRecorder.focusing(0.5f, 0.5f);
        }

        @Override
        public void onDeviceAttachFailed(int facing) {

        }

        @Override
        public void onSessionAttach() {
            if(!isRecording&&!isSessionAttach) {
                isSessionAttach=true;
                showProgressDialog("", "直播创建中");
                Log.i(TAG, "Start live stream startRecord!");
                boolean isopenlive = false;
                try {
                    Log.i("mylog","url "+pushUrl);
                    mMediaRecorder.startRecord(pushUrl);
                    isRecording=true;
                    //调用接口在后台创建
                    isopenlive = true;
                } catch (Exception e) {
                    Toast.makeText(LiveCameraActivity.this, "创建直播失败！", Toast.LENGTH_SHORT).show();
                }
                if (isopenlive) {
                    Log.v("zyl","pushUrl:"+pushUrl);
                    Log.v("zyl","playUrl:"+playUrl);
                    netRequest.requestHXOpenOneLiveRoom(1, Stores.stores_name + "直播间", "null", playUrl, Stores.stores_name + "直播间", "null", LocationApplication.im_user_id);

                }
//                //开启摄像头后开始鉴权
//                AuthTest.getInstance().initAuth(LiveCameraActivity.this, Constant.APP_KEY, Constant.APP_SECRET, Constant.SPACE);
            }
            mMediaRecorder.focusing(0.5f, 0.5f);
        }

        @Override
        public void onSessionDetach() {
        }

        @Override
        public void onDeviceDetach() {

        }

        @Override
        public void onIllegalOutputResolution() {
            Log.d(TAG, "selected illegal output resolution");

        }
    };


    private OnNetworkStatusListener mOnNetworkStatusListener = new OnNetworkStatusListener() {
        @Override
        public void onNetworkBusy() {
            Log.d("network_status", "==== on network busy ====");
            Toast toast = Toast.makeText(LiveCameraActivity.this,
                    "当前网络状态极差，已无法正常流畅直播，确认要继续直播吗？", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
            TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
            text.setGravity(Gravity.CENTER);
            toast.show();
        }

        @Override
        public void onNetworkFree() {
            Toast toast = Toast.makeText(LiveCameraActivity.this,
                    "network free", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
            TextView text = (TextView) toast.getView().findViewById(android.R.id.message);
            text.setGravity(Gravity.CENTER);
            toast.show();
            Log.d("network_status", "===== on network free ====");
        }

        @Override
        public void onConnectionStatusChange(int status) {
            switch (status) {
                case AlivcStatusCode.STATUS_CONNECTION_START:

                    Log.i(TAG, "Start live stream connection!");
                    break;
                case AlivcStatusCode.STATUS_CONNECTION_ESTABLISHED:
                    Log.i(TAG, "Live stream connection is established!");

                    break;
                case AlivcStatusCode.STATUS_CONNECTION_CLOSED:
                    Log.i(TAG, "Live stream connection is closed!");

//                    mLiveRecorder.stop();
//                    mLiveRecorder.release();
//                    mLiveRecorder = null;
                    mMediaRecorder.stopRecord();
                    break;
            }
        }
        @Override
        public boolean onNetworkReconnectFailed() {
            Log.d(TAG, "Reconnect timeout, not adapt to living");
           Toast.makeText(LiveCameraActivity.this, "长时间重连失败，已不适合直播，请退出",Toast.LENGTH_SHORT).show();
            mMediaRecorder.stopRecord();
            return false;
        }

    };

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                boolean hasPermission = true;
                String s_toasttip="";
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                        int toastTip = 0;
                        if (Manifest.permission.CAMERA.equals(permissions[i])) {
                            toastTip = 1;
                            s_toasttip= "没有权限使用摄像头，请开启摄像头权限";
                        } else if (Manifest.permission.RECORD_AUDIO.equals(permissions[i])) {
                            toastTip = 1;
                            s_toasttip= "没有权限使用录音，请开启录音权限";
                        }
                        if (toastTip != 0) {
                            Toast.makeText(this, s_toasttip, Toast.LENGTH_SHORT).show();
                            hasPermission = false;
                        }
                    }
                }
                mHasPermission = hasPermission;
                break;
        }
    }

    private OnLiveRecordErrorListener mOnErrorListener = new OnLiveRecordErrorListener() {
        @Override
        public void onError(int errorCode) {
            switch (errorCode) {
                case AlivcStatusCode.ERROR_SERVER_CLOSED_CONNECTION:
                case AlivcStatusCode.ERORR_OUT_OF_MEMORY:
                case AlivcStatusCode.ERROR_CONNECTION_TIMEOUT:
                case AlivcStatusCode.ERROR_BROKEN_PIPE:
                case AlivcStatusCode.ERROR_ILLEGAL_ARGUMENT:
                case AlivcStatusCode.ERROR_IO:
                case AlivcStatusCode.ERROR_NETWORK_UNREACHABLE:
                    Log.i(TAG, "Live stream connection error-->" + errorCode);


                    break;

                default:
            }
        }
    };

/////////////////////////////////////////////////////////////////////////////////
//以上代码基本都是趣拍的代码  以下代码基本是自己的代码
    @Override
    public void onBackPressed() {
    super.onBackPressed();
    if (!TextUtils.isEmpty(room_id)) {
        setHXCMD(false, "");
        netRequest.requestHXCloseOneLiveRoom(2, LocationApplication.im_user_id, room_id);
     }
    }

    public void setHXCMD(boolean isStart, String url) {
        EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
        Log.i("mylog", "直播透传" + isStart);
        //支持单聊和群聊，默认单聊，如果是群聊添加下面这行
        cmdMsg.setTo(room_id);
        cmdMsg.setChatType(EMMessage.ChatType.ChatRoom);

        EMCmdMessageBody cmdBody = new EMCmdMessageBody("closeRoom");
        cmdMsg.addBody(cmdBody);
        EMClient.getInstance().chatManager().sendMessage(cmdMsg);


    }
    @Override
    public void onAfinalFail() {
        dismissProgressDialog();
        //开始直播并推流
        Toast.makeText(LiveCameraActivity.this, "请检查本地网络！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {

            try {
                dismissProgressDialog();
                Toast.makeText(LiveCameraActivity.this, "开始直播！", Toast.LENGTH_SHORT).show();
                JSONObject jsonObject = new JSONObject(result);
                room_id = jsonObject.getString("id");
                Log.i("mylog", "id " + room_id);
                if (editor != null) {
                    editor.putString("live_room_id", room_id).apply();
                }
                if (!LiveCameraActivity.this.isFinishing()) {
                    chatFragment = new EaseChatFragment_Live();
                    Bundle bundle = new Bundle();
                    bundle.putString(EaseConstant.EXTRA_USER_ID, room_id);
                    //pass parameters to chat fragment
                    chatFragment.setArguments(bundle);
                    getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commitAllowingStateLoss();
                }
            } catch (Exception e) {
                if (!TextUtils.isEmpty(room_id)) {
                    netRequest.requestHXCloseOneLiveRoom(2, LocationApplication.im_user_id, room_id);
                }
                e.printStackTrace();
            }

        } else if (requestId == 2) {
            Log.i("mylog", "退出直播请求 " + result);
        }


    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (requestId == 1) {
            Log.i("mylog", msg);
            dismissProgressDialog();
            //开始直播并推流
            Toast.makeText(LiveCameraActivity.this, "创建直播失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
        } else if (requestId == 2) {
            Log.i("mylog", "222eeeee " + msg);
            Toast.makeText(LiveCameraActivity.this, "关闭直播失败！(" + msg + ")", Toast.LENGTH_SHORT).show();
        }
    }


//    /**
//     * 创建直播,并得到推拉流地址
//     * LiveService.getInstance().createLive(“鉴权后得到的AccessToken”,
//     * “用户唯一标记【建议使用uid】”， ”直播地址【http://+控制台提供的访问域名】“）；
//     */
//    private void createLive() {
//        LiveService.getInstance().createLive(Constant.accessToken, Constant.SPACE, Constant.LIVE_URL);
//        LiveService.getInstance().setCreateLiveListener(new CreateLiveListener() {
//            @Override
//            public void onCreateLiveError(int errorCode, String message) {
//                Log.e("live", "errorCode:" + errorCode + "message" + message);
//                dismissProgressDialog();
//                //开始直播并推流
//                Toast.makeText(LiveCameraActivity.this, "创建直播失败！", Toast.LENGTH_SHORT).show();
//            }
//
//
//            @Override
//            public void onCreateLiveSuccess(String pushUrl, String playUrl) {
//                Log.e("live", "pushUrl:" + pushUrl + "playUrl" + playUrl);
//                Log.i("mylog", "播放链接 " + playUrl);
//                startRecorder(pushUrl, playUrl);
//            }
//        });
//
//    }
//    private void startRecorder(String pushUrl, String playUrl) {
//        Log.i(TAG, "Start live stream startRecord!");
//        boolean isopenlive = false;
//        try {
//            Log.i("mylog","url "+pushUrl);
//            mMediaRecorder.startRecord(pushUrl);
//            isRecording=true;
//            //调用接口在后台创建
//            isopenlive = true;
//        } catch (Exception e) {
//            Toast.makeText(LiveCameraActivity.this, "创建直播失败！", Toast.LENGTH_SHORT).show();
//        }
//        if (isopenlive) {
//            netRequest.requestHXOpenOneLiveRoom(1, Stores.stores_name + "直播间", "null", playUrl, Stores.stores_name + "直播间", "null", LocationApplication.im_user_id);
//
//        }
//    }

//    //鉴权eventbus
//    public void onEventMainThread(SignBean signBean) {
//        Log.v("zyl", "onEvent");
//        String sing = signBean.sign;
//        //代表鉴权成功
//        if (sing.equals("001")) {
//            Log.v("zyl", "收到鉴权成功信号");
//            //开始直播并推流
//            createLive();
//        } else if (sing.equals("002")) {
//            Log.v("zyl", "收到鉴权成功信号");
//
//            dismissProgressDialog();
//            //开始直播并推流
//            Toast.makeText(LiveCameraActivity.this, "创建直播失败！", Toast.LENGTH_SHORT).show();
//        }
//    }
    //聊天室传出来的eventbus 关闭页面
    public void onEvent(LiveBean liveBean) {
        if (liveBean.type == 1) {
            setHXCMD(false, "");
            netRequest.requestHXCloseOneLiveRoom(2, LocationApplication.im_user_id, room_id);
            Toast.makeText(LiveCameraActivity.this, "创建直播失败！", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    protected void showProgressDialog(String title, String msg) {
        if (mProgressDialog == null || !mProgressDialog.getContext().equals(this)) {
            mProgressDialog = new ProgressDialog(this);
        }
        if (!TextUtils.isEmpty(title)) {
            mProgressDialog.setTitle(title);
        }
        mProgressDialog.setMessage(msg);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }


    protected void dismissProgressDialog() {
        try {
            if (mProgressDialog != null)
                mProgressDialog.dismiss();
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            //镜头切换
            case R.id.tv_camera:
                int currFacing = mMediaRecorder.switchCamera();
                if(isRecording) {
                    if (currFacing == AlivcMediaFormat.CAMERA_FACING_FRONT) {
                        mMediaRecorder.addFlag(AlivcMediaFormat.FLAG_BEAUTY_ON);
                    }
                    mConfigure.put(AlivcMediaFormat.KEY_CAMERA_FACING, currFacing);
                }else{
                    Toast.makeText(this,"摄像头开启中，请稍后重试",Toast.LENGTH_SHORT).show();
                }
                break;
            //美颜切换
            case R.id.tv_beauty:
                if(isRecording) {
                if (ifOpenBeauty) {
                    Log.i("mylog","美颜on");
                    mMediaRecorder.addFlag(AlivcMediaFormat.FLAG_BEAUTY_ON);
                    Toast.makeText(this,"开启美颜功能！",Toast.LENGTH_SHORT).show();
                } else {
                    Log.i("mylog", "美颜off");
                    mMediaRecorder.removeFlag(AlivcMediaFormat.FLAG_BEAUTY_ON);
                    Toast.makeText(this,"关闭美颜功能！",Toast.LENGTH_SHORT).show();
                }
                ifOpenBeauty = !ifOpenBeauty;
                }else{
                    Toast.makeText(this,"摄像头开启中，请稍后重试",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.tv_return:
                if (!TextUtils.isEmpty(room_id)) {
                    setHXCMD(false, "");
                    netRequest.requestHXCloseOneLiveRoom(2, LocationApplication.im_user_id, room_id);
                }
                finish();
                break;
        }
    }

    private static String MD5(String sourceStr) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(sourceStr.getBytes());
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
        }
        return "";
    }
}
